const {
  ipcMain,
  Menu,
  MessageChannelMain,
  nativeTheme,
  MenuItem,
  globalShortcut,
  Notification,
  nativeImage,
  ThumbarButton,
} = require("electron");
const { app, BrowserWindow } = require("electron/main");
const path = require("node:path");
const fs = require("node:fs");

// app.disableHardwareAcceleration()

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    icon: path.join(__dirname, "icon.png"),
    width: 800,
    height: 600,
    // frame: false,
    // transparent: true,
    webPreferences: {
      // offscreen: true,
      preload: path.join(__dirname, "preload.js"),
    },
    titleBarStyle: "hidden",
    // expose window controls in Windows/Linux
    ...(process.platform !== "darwin" ? { titleBarOverlay: true } : {}),
  });

  // 截图 (软件输出设备 offscreen：true)
  // mainWindow.webContents.on('paint', (event, dirty, image) => {
  //   fs.writeFileSync('ex.png', image.toPNG())
  // })
  // mainWindow.webContents.setFrameRate(60)
  // console.log(`The screenshot has been successfully saved to ${path.join(process.cwd(), 'ex.png')}`)

  // const win2 = new BrowserWindow({ width: 800, height: 1500 });
  // win2.loadURL("https://github.com");

  ipcMain.on("set-title", (event, title) => {
    const webContents = event.sender;
    const win = BrowserWindow.fromWebContents(webContents);
    win.setTitle(title);
  });

  // const menu = Menu.buildFromTemplate([
  //   {
  //     label: app.name,
  //     submenu: [
  //       {
  //         click: () => mainWindow.webContents.send("update-counter", 1),
  //         label: "Increment",
  //       },
  //       {
  //         click: () => mainWindow.webContents.send("update-counter", -1),
  //         label: "Decrement",
  //       },
  //     ],
  //   },
  // ]);
  // Menu.setApplicationMenu(menu);

  const menu2 = new Menu();
  menu2.append(
    new MenuItem({
      label: "Electron",
      submenu: [
        {
          role: "help",
          accelerator:
            process.platform === "darwin" ? "Alt+Cmd+I" : "Alt+Shift+I",
          click: () => {
            console.log("Electron rocks!");
          },
        },
      ],
    })
  );
  Menu.setApplicationMenu(menu2);

  // MessageChannel
  const { port1, port2 } = new MessageChannelMain();
  port2.postMessage({ test: 21 });
  port2.on("message", (event) => {
    console.log("来自渲染进程的消息:", event.data);
  });
  port2.start();
  mainWindow.webContents.postMessage("main-world-port", null, [port1]);

  // 主题
  ipcMain.handle("dark-mode:toggle", () => {
    if (nativeTheme.shouldUseDarkColors) {
      nativeTheme.themeSource = "light";
    } else {
      nativeTheme.themeSource = "dark";
    }
    return nativeTheme.shouldUseDarkColors;
  });

  ipcMain.handle("dark-mode:system", () => {
    nativeTheme.themeSource = "system";
  });

  // 拖 & 放
  const iconName = path.join(__dirname, "iconForDragAndDrop.png");
  // const icon = fs.createWriteStream(iconName);

  // // Create a new file to copy - you can also copy existing files.
  // fs.writeFileSync(
  //   path.join(__dirname, "drag-and-drop-1.md"),
  //   "# First file to test drag and drop"
  // );
  // fs.writeFileSync(
  //   path.join(__dirname, "drag-and-drop-2.md"),
  //   "# Second file to test drag and drop"
  // );

  // https.get("https://img.icons8.com/ios/452/drag-and-drop.png", (response) => {
  //   response.pipe(icon);
  // });

  let dragSourceWindow = null;
  ipcMain.on("ondragstart", (event, filePath) => {
    dragSourceWindow = event.sender;
    event.sender.startDrag({
      file: path.join(__dirname, filePath),
      icon: iconName, // windows使用32*32的图标
    });
  });
  app.on("browser-window-focus", () => {
    if (dragSourceWindow) {
      dragSourceWindow.send("ondragend", { success: true });
      dragSourceWindow = null;
    }
  });

  mainWindow.loadFile("index.html");
};

app
  .whenReady()
  .then(() => {
    globalShortcut.register("Alt+CommandOrControl+I", () => {
      console.log("Electron loves global shortcuts!");
    });
  })
  .then(() => {
    createWindow();

    // app.setJumpList([
    //   {
    //     type: 'custom',
    //     name: 'Recent Projects',
    //     items: [
    //       { type: 'file', path: 'E:\\demo\\electron\\drag-and-drop-1.md' },
    //       { type: 'file', path: 'E:\\demo\\electron\\drag-and-drop-2.md' }
    //     ]
    //   }
    // ])
    
    app.on("activate", () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
      }
    });
  })
  .then(() => {
    // const NOTIFICATION_TITLE = "Basic Notification";
    // const NOTIFICATION_BODY = "Notification from the Main process";
    // new Notification({
    //   title: NOTIFICATION_TITLE,
    //   body: NOTIFICATION_BODY,
    // }).show();
  });

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});
